import 'package:sqflite/sqflite.dart';

class MSDatabaseUtil{
  static final MSDatabaseUtil _instance =MSDatabaseUtil._();
  MSDatabaseUtil._();
  factory MSDatabaseUtil(){
    return _instance;
  }

  Database? _database;

  init()async{
     _database = await openDatabase("ms.db",version: 1,onCreate: (Database db, int version)async{
       await db.execute(
           'CREATE TABLE Category (id INTEGER PRIMARY KEY, name TEXT, userId TEXT, time TEXT)');
       await db.execute(
           'CREATE TABLE Task (id INTEGER PRIMARY KEY, name TEXT, isFinished INTEGER,userId TEXT, categoryId INTEGER, time TEXT)');

       await db.execute(
           'CREATE TABLE Milestone (id INTEGER PRIMARY KEY, type INTEGER, userId TEXT, content TEXT, month INTEGER)');
    });
  }

  Future<int?> insert(String table,Map<String,dynamic> value)async{
    return await _database?.insert(
        table,value,conflictAlgorithm: ConflictAlgorithm. replace);
  }

  Future<List<Map<String, Object?>>?> query(String table,List<String> columns,List<String> key, List<dynamic> conditions)async{
    return  await _database?.query(table,
        columns: columns,
        where: key.map((e) => '$e = ?').join(" and "),
        whereArgs: conditions);
  }

  Future<int?> update(String table,Map<String,dynamic> value,String key, List<dynamic> conditions)async{
    return  await _database?.update(table,
        value,
        where: '$key = ?',
        whereArgs: conditions);
  }

  Future<int?> delete(String table,List<String> key, List<dynamic> conditions)async{
    return  await _database?.delete(table,
        where: key.map((e) => '$e = ?').join(" and "),
        whereArgs: conditions);
  }
}